<template>
    <div class="table-container">
        <el-breadcrumb separator="/" class="header">
            <el-breadcrumb-item>笔记代码</el-breadcrumb-item>
        </el-breadcrumb>

        <div class="filter-container">
            <el-select v-model="selectedOption" clearable placeholder="所有笔记" style="width: 128px"
                @change="handleOptionChange" @clear="selectedOption = ''">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>

            <el-input v-model="searchVideoTitle" style="width: 200px" placeholder="请输入标题" clearable
                @clear="handleClearSearch" @keyup.enter="handleSearch">
                <template #prefix>
                    <el-icon class="el-input__icon">
                        <search />
                    </el-icon>
                </template>
            </el-input>

            <el-select v-model="searchUp" filterable clearable remote reserve-keyword placeholder="搜索up主"
                style="width: 200px" :remote-method="filterUpList" :loading="upListLoading" @clear="handleClearUpSearch"
                @change="handleSearch">
                <el-option v-for="item in filteredUpList" :key="item" :label="item" :value="item" />
            </el-select>

            <el-date-picker v-model="selectedDate" type="date" placeholder="选择日期" style="width: 200px" :clearable="true"
                @change="handleDateChange">
                <template #suffix-icon>
                    <el-icon>
                        <calendar />
                    </el-icon>
                </template>
            </el-date-picker>

            <el-input v-model="searchSecretCode" style="width: 200px" placeholder="搜索笔记暗号" clearable
                @clear="handleClearSecretCode" @keyup.enter="handleSearch" :debounce="300">
                <template #prefix>
                    <el-icon class="el-input__icon">
                        <search />
                    </el-icon>
                </template>
            </el-input>
        </div>

        <el-alert v-if="error" :title="error" type="error" show-icon class="mb-20" />
        <el-skeleton v-if="loading" :rows="6" animated />

        <el-table v-else :data="tableData" style="width: 100%" height="calc(100vh - 250px)" :fit="true" v-loading="loading">
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="title" label="标题" width="200" show-overflow-tooltip />
            <el-table-column prop="chapter" label="课程章节" width="180" />
            <el-table-column prop="up" label="up主" width="180" />
            <el-table-column prop="note" label="笔记" width="120">
                <template #default="scope">
                    <span :class="getNotePlatformClass(scope.row.note)">
                        <span class="note-dot"></span>
                        {{ scope.row.note || '未知' }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="date" label="日期" width="120" />
            <el-table-column prop="code" label="暗号" width="120" />
            <el-table-column fixed="right" prop="link" label="链接" width="100">
                <template #default="scope">
                    <el-link type="primary" @click="handleCopyAndOpenLink(scope.row.link)" class="copy-open-link">
                        复制/打开
                    </el-link>
                </template>
            </el-table-column>
            <el-table-column fixed="right" prop="address" label="笔记网盘地址" width="120">
                <template #default="scope">
                    <el-link type="primary" @click="handleCopyOnly(scope.row.address)" class="copy-open-link">
                        复制
                    </el-link>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination v-model:current-page="pagination.pageNum" v-model:page-size="pagination.pageSize" size="small"
            layout=" prev, pager, next, jumper" :total="pagination.total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" class="pagination-container" />
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Search, Calendar } from '@element-plus/icons-vue'
import { listNotes, getUploaderList } from '../../../api/media/note'
import { ElMessage } from 'element-plus'

const searchVideoTitle = ref('')
const searchUp = ref('')
const selectedOption = ref('')
const selectedDate = ref('')
const searchSecretCode = ref('')
const loading = ref(false)
const error = ref(null)
const upListLoading = ref(false)
const upList = ref([])
const filteredUpList = ref([])

const pagination = ref({
    pageNum: 1,
    pageSize: 20,
    total: 0
})

const tableData = ref([])

const options = [
    { value: '', label: '所有笔记' },
    { value: 'B站', label: 'B站' },
    { value: '小红书', label: '小红书' },
    { value: '抖音', label: '抖音' }
]

const formatDate = (date) => {
    if (!date) return ''
    const d = new Date(date)
    const year = d.getFullYear()
    const month = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
}

const fetchNotes = async () => {
    loading.value = true;
    error.value = null;
    try {
        const params = {
            pageNum: pagination.value.pageNum,
            pageSize: pagination.value.pageSize,
            ...(searchVideoTitle.value && { videoTitle: searchVideoTitle.value }),
            ...(searchUp.value && { uploader: searchUp.value }),
            ...(selectedOption.value && { noteType: selectedOption.value }),
            ...(selectedDate.value && { recordDate: formatDate(selectedDate.value) }),
            ...(searchSecretCode.value && { secretCode: searchSecretCode.value })
        };

        const res = await listNotes(params);

        tableData.value = res.rows.map((item) => ({
            id: item.id,
            date: item.recordDate,
            up: item.uploader,
            note: item.noteType,
            chapter: item.courseChapter,
            title: item.videoTitle,
            link: item.videoLink,
            address: item.notesLink,
            code: item.secretCode,
        }));

        pagination.value.total = res.total;
    } catch (err) {
        error.value = `请求失败: ${err.response?.data?.message || err.message}`;
        console.error("获取笔记列表失败:", err);
    } finally {
        loading.value = false;
    }
};

const fetchUploaderList = async () => {
    try {
        upListLoading.value = true
        const res = await getUploaderList()
        upList.value = [...new Set(res.rows.map(item => item.uploader).filter(uploader => uploader))]
        filteredUpList.value = [...upList.value]
    } catch (err) {
        console.error('获取UP主列表失败:', err)
        ElMessage.error('获取UP主列表失败: ' + (err.response?.data?.msg || err.message))
    } finally {
        upListLoading.value = false
    }
}

const filterUpList = (query) => {
    if (query) {
        filteredUpList.value = upList.value.filter(uploader =>
            uploader.toLowerCase().includes(query.toLowerCase())
        )
    } else {
        filteredUpList.value = [...upList.value]
    }
}

const handleSearch = () => {
    pagination.value.pageNum = 1;
    fetchNotes();
};

const handleSizeChange = (val) => {
    pagination.value.pageSize = val;
    fetchNotes();
};

const handleCurrentChange = (val) => {
    pagination.value.pageNum = val;
    fetchNotes();
};

const handleClearSearch = () => {
    searchVideoTitle.value = '';
    handleSearch();
};

const handleClearUpSearch = () => {
    searchUp.value = '';
    handleSearch();
};

const handleClearSecretCode = () => {
    searchSecretCode.value = ''
    handleSearch()
}

const handleOptionChange = (val) => {
    selectedOption.value = val === null ? '' : val;
    handleSearch()
}

const handleDateChange = () => {
    handleSearch();
}

const getNotePlatformClass = (noteType) => {
    switch (noteType) {
        case 'B站': return 'bz-note'
        case '小红书': return 'xhs-note'
        case '抖音': return 'dy-note'
        default: return ''
    }
}

const handleCopyAndOpenLink = (url) => {
    const pureUrlMatch = url.match(/https?:\/\/[^\s]+/);
    const pureUrl = pureUrlMatch ? pureUrlMatch[0] : url;

    const textarea = document.createElement('textarea');
    textarea.value = pureUrl;
    document.body.appendChild(textarea);
    textarea.select();

    try {
        const successful = document.execCommand('copy');
        if (successful) {
            ElMessage.success('链接已复制');
        } else {
            ElMessage.warning('无法自动复制，请手动复制链接');
        }
    } catch (err) {
        console.error('复制失败:', err);
        ElMessage.warning('无法自动复制，请手动复制链接');
    }

    document.body.removeChild(textarea);

    window.shellAPI.openExternal(pureUrl).catch(err => {
        console.error('无法打开链接:', err);
    });
};

const handleCopyOnly = (url) => {
    const pureUrlMatch = url.match(/https?:\/\/[^\s]+/);
    const pureUrl = pureUrlMatch ? pureUrlMatch[0] : url;

    const textarea = document.createElement('textarea');
    textarea.value = pureUrl;
    document.body.appendChild(textarea);
    textarea.select();

    try {
        const successful = document.execCommand('copy');
        if (successful) {
            ElMessage.success('链接已复制');
        } else {
            ElMessage.warning('无法自动复制，请手动复制链接');
        }
    } catch (err) {
        console.error('复制失败:', err);
        ElMessage.warning('无法自动复制，请手动复制链接');
    }

    document.body.removeChild(textarea);
};

onMounted(() => {
    fetchNotes()
    fetchUploaderList()
})
</script>

<style scoped>
.header {
    margin-bottom: 5px;
    padding: 15px 0;
    font-size: 20px;
}

.table-container {
    width: 100%;
    overflow-x: auto;
    box-sizing: border-box;
}

.filter-container {
    display: flex;
    gap: 12px;
    margin-bottom: 20px;
    flex-wrap: wrap;
    align-items: center;
}

.note-dot {
    display: inline-block;
    width: 6px;
    height: 6px;
    border-radius: 50%;
    margin-right: 6px;
}

.bz-note .note-dot {
    background-color: #00aeec;
}

.xhs-note .note-dot {
    background-color: #ff2442;
}

.dy-note .note-dot {
    background-color: #010000;
}

.bz-note,
.xhs-note,
.dy-note {
    display: flex;
    color: #747474;
    align-items: center;
}

.pagination-container {
    margin-top: 20px;
    justify-content: flex-end;
}

@media (max-width: 768px) {
    .el-table {
        font-size: 12px;
    }

    .el-button {
        padding: 5px;
        font-size: 12px;
    }

    .el-table-column {
        width: auto !important;
    }

    .filter-container {
        flex-direction: column;
        align-items: flex-start;
    }
}
</style>